#include "gy39.h"


GY39::GY39(QObject *parent) : QSerialPort(parent)
{
    setPortName("/dev/ttySAC2"); // 设置为你的串口号
    setBaudRate(QSerialPort::Baud9600); // 设置波特率
    setDataBits(QSerialPort::Data8); // 设置数据位
    setParity(QSerialPort::NoParity); // 设置无校验
    setStopBits(QSerialPort::OneStop); // 设置停止位

    if (open(QIODevice::ReadWrite))
    { // 打开串口
        qDebug() << "GY39 Port1 opened successfully!";

        connect(this, &QSerialPort::readyRead, this, &GY39::handleReadyRead);

    }
    else
    {
        qDebug() << "Failed to open port:" << errorString();
        return ;
    }

    timer = new QTimer(this);
    timer->setInterval(10);
    timer->setSingleShot(true);
}

void GY39::handleReadyRead()
{
    QByteArray response = readAll();
    //qDebug() << response.toHex();
    static int count = 0;

    if(!timer->isActive())
    {
        count++;
        if(count >= 3)
        {
            count = 0;
            timer->start();
        }
        emit sigRecvData(response);

    }
#if 0
    buffer.append(response);

LABEL:
    int index = 0;
    if(buffer.size() >= 9)
    {
        if(buffer.at(0) == 0x5A && buffer.at(1) == 0x5A)
        {
            index = 2;
            if(buffer.at(2) == 0x15 && buffer.at(3) == 0x04)
            {
                QByteArray frame = buffer.mid(0, 9);
                // 校验和验证
                if (verifyChecksum(frame))
                {
                    // 解析数据
                    quint16 dataFront = (static_cast<quint8>(frame[4]) << 8) | static_cast<quint8>(frame[5]);
                    quint16 dataBack = (static_cast<quint8>(frame[6]) << 8) | static_cast<quint8>(frame[7]);

                    quint32 tmp = (dataFront << 16) | dataBack;
                    static quint32 light = 0;
                    if(light != tmp)
                    {
                        light = tmp;
                        emit sigLight(light / 100.0);
                        qDebug() << "light:" << light;
                    }
                    index = 9;
                }
            }
            else if(buffer.at(2) == 0x45 && buffer.size() >= 12)
            {
                if(buffer.at(3) == 0x0A)
                {
                    index = 12;

                    QByteArray frame = buffer.mid(0, 15);
                    if (verifyChecksum(frame, frame.at(14)))
                    {
                        // 解析温度
                        quint16 temperatureRaw = (static_cast<quint8>(frame[4]) << 8) | static_cast<quint8>(frame[5]);
                        float temperature = static_cast<float>(temperatureRaw) / 100.0;

                        // 解析气压
                        quint32 pressureRaw = (static_cast<quint32>(frame[6]) << 24) |
                                              (static_cast<quint32>(frame[7]) << 16) |
                                              (static_cast<quint32>(frame[8]) << 8) |
                                              static_cast<quint32>(frame[9]);
                        float pressure = static_cast<float>(pressureRaw) / 100.0;

                        // 解析湿度
                        quint16 humidityRaw = (static_cast<quint8>(frame[10]) << 8) | static_cast<quint8>(frame[11]);
                        float humidity = static_cast<float>(humidityRaw) / 100.0;

                        // 解析海拔
                        quint16 altitudeRaw = (static_cast<quint8>(frame[12]) << 8) | static_cast<quint8>(frame[13]);
                        float altitude = static_cast<float>(altitudeRaw) / 1.0;

                        qDebug() << "Temperature:" << temperature << "°C";
                        qDebug() << "Pressure:" << pressure << "hPa";
                        qDebug() << "Humidity:" << humidity << "%";
                        qDebug() << "Altitude:" << altitude << "m";
                        emit sigData(temperature, humidity);
                    }
                    else
                        qDebug() << "verify Checksum fail";
                }
            }
        }
    }

    if(index != 9 && index != 12)
    {
        while (buffer.at(index)!=0x5A && index <= buffer.size())
        {
            index++;
        }
    }
    //qDebug() << "index=" <<index;
    // 移除已经处理过的数据
    buffer = buffer.mid(index);
    if(buffer.size() >= 9)
    {
        goto LABEL;
    }
#endif
}

bool GY39::verifyChecksum(const QByteArray &data)
{
    quint8 sum = 0;
    for (int i = 0; i < 8; ++i) {
        sum += static_cast<quint8>(data[i]);
    }
    return sum == static_cast<quint8>(data[8]);
}

bool GY39::verifyChecksum(const QByteArray &data, quint8 crc)
{
    quint8 sum = 0;
    for (int i = 0; i < 14; ++i) {
        sum += static_cast<quint8>(data[i]);
    }
    //qDebug() << sum << crc;
    return sum == crc;
}
